from django.shortcuts import render
from common.models import Types
from datetime import datetime
import hashlib

# Create your views here.
def index(request):
    '''浏览商品类别列表'''
    typeslist=Types.objects.extra(select={'_has':'concat(path,id)'}).order_by('_has')
    for types in typeslist:
        types.pname = '. . . ' * (types.path.count(',') - 1)
    context={"typeslist":typeslist}
    return render(request,'admin/types/index.html',context)

def add(request,tid):
    '''加载添加页面'''
    # 获取父类别信息，如果没有则默认为根类别
    if tid == "0":
        context = {"pid": 0, "path": "0,", "name": "根类别"}
    else:
        pobj = Types.objects.get(id=tid)  # 父级信息
        context = {"pid": pobj.id, "path": pobj.path + str(pobj.id) + ",", "name": pobj.name}
    return render(request, 'admin/types/add.html', context)

def insert(request):
    '''执行添加'''
    try:
        tobj=Types()
        tobj.name=request.POST["name"]
        tobj.pid = request.POST["pid"]
        tobj.path = request.POST["path"]
        tobj.save()
        context = {"info": "添加成功！"}
    except Exception as err:
        context={"info":"添加失败！"}
    return render(request,'admin/info.html',context)

def delete(request,tid):
    '''删除商品类别'''
    try:
        # 如果当前类别下还有子类别，则提示先删除子类别
        childrenCount=Types.objects.filter(pid=tid).count()
        if childrenCount>0:
            context = {'info': '删除失败：此类别下还有子类别！'}
        else:
            tobj=Types.objects.get(id=tid)
            tobj.delete()
            context = {"info": "删除成功！"}
    except Exception as err:
        context={"info":"删除失败！"}
    return render(request,'admin/info.html',context)

def edit(request,tid):
    '''加载编辑商品类别信息'''
    try:
        print(tid)
        tobj=Types.objects.get(id=tid)
        context={'types':tobj}
        return render(request, 'admin/types/edit.html',context)
    except Exception as err:
        context={"info":"查询商品类别信息失败！"+str(err)}
    return render(request,'admin/info.html',context)

def update(request,tid):
    '''执行商品类别编辑'''
    try:
        tobj = Types.objects.get(id=tid)
        tobj.name = request.POST["name"]
        tobj.save()
        context = {"info": "修改成功！"}
    except Exception as err:
        context={"info":"修改失败！"}
    return render(request,'admin/info.html',context)